package Database;

import Entity.Duration;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author CONG
 */
public class DurationDB {
    private ConnectDB conn;

    public DurationDB() {
        conn=new ConnectDB();
    }
    public  ArrayList<Duration>  getDurationList(){
        ArrayList<Duration> listDur=new ArrayList<Duration>();
        try {
            CallableStatement cstmt=conn.connect().prepareCall("{call getDurationList}");
            ResultSet rs=cstmt.executeQuery();
            while(rs.next()){
                int account=rs.getInt("AccountLoanCode");
                int loanCode=rs.getInt("LoanTypeCode");
                Date startdate=rs.getDate("StartDate");
                float amountLoan=rs.getFloat("AmountLoan");
                Date endDate=rs.getDate("EndDate");
                float balance=rs.getFloat("Balance");
                boolean status=rs.getBoolean("LoanStatus");
                boolean accept=rs.getBoolean("Accepted");
               Duration dur=new Duration(account, loanCode, startdate, amountLoan, endDate, balance, status, accept);
               listDur.add(dur);
            }
        } catch (Exception ex) {
            Logger.getLogger(DurationDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return listDur;
    }
    public Duration insertDuration(Duration dur){
        try {
            CallableStatement cstmt=conn.connect().prepareCall("{call insertDuration(?,?,?,?,?,?)}");
            cstmt.registerOutParameter("accountLoanCode", Types.INTEGER);
            cstmt.setInt("loanTypeCode", dur.getLoanTypeCode());
            cstmt.setDate("startDate",new java.sql.Date(dur.getStartDate().getTime()));
            cstmt.setFloat("amountLoan", dur.getAmountLoan());
            cstmt.setDate("endDate", new java.sql.Date(dur.getEndDate().getTime()));
            cstmt.setFloat("balance", dur.getBalance());
            cstmt.executeUpdate();
            int accountLoanCode=cstmt.getInt("AccountLoanCode");
            dur.setAccountLoanCode(accountLoanCode);
        } catch (Exception ex) {
            Logger.getLogger(DurationDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return dur;
    }
}
